﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bosphorus.Migrator.Dialect.Core;
using Bosphorus.Migrator.Core.MigrationCommand;
using Bosphorus.Migrator.Core.Command.Grouper;

namespace Bosphorus.Migrator.Dialect.NVelocity
{
    public class NVelocityDialectAdapter<TModel> : AbstractDialect<AbstractCommand<TModel>>
    {
        private readonly IDialect nvelocityDialect;

        public NVelocityDialectAdapter(IDialect nvelocityDialect)
        {
            this.nvelocityDialect = nvelocityDialect;
        }

        public override string Create(AbstractCommand<TModel> model)
        {
            //NVelocityModel nvelocityModel = BuildNVelocityModel(model);
            //string dialectedResult = nvelocityDialect.Create()
            //return dialectedResult;
            return string.Empty;
        }

        public override string Alter(AbstractCommand<TModel> model)
        {
            //NVelocityModel nvelocityModel = BuildNVelocityModel(model);
            //string dialectedResult = nvelocityDialect.Create(nvelocityModel);
            //return dialectedResult;
            return string.Empty;
        }

        public override string Drop(AbstractCommand<TModel> model)
        {
            //NVelocityModel nvelocityModel = BuildNVelocityModel(model);
            //string dialectedResult = nvelocityDialect.Drop(nvelocityModel);
            //return dialectedResult;
            return string.Empty;
        }

        private NVelocityModel BuildNVelocityModel(ICommand command)
        {
            NVelocityModel nvelocityModel = new NVelocityModel(command.Model);
            IDictionary<string, IList<ICommand>> commandTypeDictionary = CommandGrouper.ByCommandType(command.SubCommands);

            foreach (string commandType in commandTypeDictionary.Keys)
            {
                IList<ICommand> commandList = commandTypeDictionary[commandType];
                IDictionary<string, IList<ICommand>> modelNameDictionary = CommandGrouper.ByModel(commandList);
                foreach (string modelName in modelNameDictionary.Keys)
                {
                    IList<ICommand> modelNameCommandList = modelNameDictionary[modelName];
                    foreach (ICommand subCommand in modelNameCommandList)
                    {
                        NVelocityModel subNVelocityModel = BuildNVelocityModel(subCommand);
                        nvelocityModel[commandType][modelName].Add(subNVelocityModel);
                    }
                }
            }
            return nvelocityModel;
        }
    }
}
